<?php

namespace App\Http\Controllers\API;

use App\Admin\Models\Administrator;
use App\Admin\Services\WorkOrderService;
use App\Http\Controllers\Controller;
use App\Http\Resources\WorkOrderCollection;
use App\Http\Resources\WorkOrderDetailResource;
use App\Http\Resources\WorkOrderResource;
use App\Models\Car;
use App\Models\ComponentMaintenance;
use App\Models\ProcessesArchive;
use App\Models\StopReworkReason;
use App\Models\UserProcess;
use App\Models\WorkOrder;
use App\Models\WorkOrderComponent;
use App\Models\WorkOrderDispatch;
use App\Admin\Services\WorkOrderOperationLog;
use App\Models\WorkOrderPic;
use App\Models\WorkOrderStopRework;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{

    protected $model = WorkOrder::class;
    protected $collection = WorkOrderCollection::class;
    protected $resource = WorkOrderResource::class;

    public function indexTopAll(Request $request)
    {
        $user = Auth::user();

        $keyword = '';

        $param = $request->all();

        if (isset($param['keywords'])) {
            $keyword = $param['keywords'];
        }

        $user_workshop_id = $user->workshop_id;

        //在厂车辆
        $in_factory_count = WorkOrder::whereBetween('status', [0, 16])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //施工车辆
        $in_production_count = WorkOrder::whereBetween('status', [1, 15])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //待修车辆
        $pending_repair_count = WorkOrder::where('status', 0)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //返工车辆
        $rework_count = WorkOrder::where('is_return', DEFAULT_TRUE)
            ->whereOr('is_rework', DEFAULT_TRUE)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');

        //今日进厂
        $today_in_count = WorkOrder::whereBetween('created_at', [$today_start, $today_end])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //中断车辆
        $interrupted_count = WorkOrder::where('is_stop', DEFAULT_TRUE)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //延迟交车
        $delayed_count = WorkOrder::where('pre_delivery_at', '<' ,date('Y-m-d H:i:s'))
            ->where('status', '<', ORDER_WAIT_PAY)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //今日应交
        $due_today_count = WorkOrder::whereBetween('pre_delivery_at', [$today_start, $today_end])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //今日已交
        $delivered_today_count = WorkOrder::whereBetween('settlement_at', [$today_start, $today_end])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        $tomorrowStart = new \DateTime('tomorrow');
        $tomorrow_start = $tomorrowStart->format('Y-m-d 00:00:00');

        // 获取明天的结束时间（23:59:59）
        $tomorrowEnd = new \DateTime('tomorrow');
        $tomorrow_end = $tomorrowEnd->format('Y-m-d 23:59:59');

        //明日应交
        $due_tomorrow_count = WorkOrder::whereBetween('pre_delivery_at', [$tomorrow_start, $tomorrow_end])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        return $this->success([
            'in_factory_count' => $in_factory_count,
            'in_production_count' => $in_production_count,
            'pending_repair_count' => $pending_repair_count,
            'rework_count' => $rework_count,
            'today_in_count' => $today_in_count,
            'interrupted_count' => $interrupted_count,
            'delayed_count' => $delayed_count,
            'due_today_count' => $due_today_count,
            'delivered_today_count' => $delivered_today_count,
            'due_tomorrow_count' => $due_tomorrow_count,
        ]);
    }

    public function indexBottomAll(Request $request)
    {
        $user = Auth::user();

        $user_workshop_id = $user->workshop_id;

        $keyword = '';

        $param = $request->all();

        if (isset($param['keywords'])) {
            $keyword = $param['keywords'];
        }

        //待维修
        $data['pending'] = WorkOrder::where('status', ORDER_WAIT_MAINTENANCE)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待钣金拆解
        $data['waiting_disassembly'] = WorkOrder::where('status', ORDER_WAIT_PLATE_REMOVE)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //钣金拆解
        $data['disassembly'] = WorkOrder::where('status', ORDER_PLATE_REMOVE)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待钣金整形
        $data['waiting_shaping'] = WorkOrder::where('status', ORDER_WAIT_PLATE_RESHAPING)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //钣金整形
        $data['shaping'] = WorkOrder::where('status', ORDER_PLATE_RESHAPING)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待油漆做底
        $data['waiting_priming'] = WorkOrder::where('status', ORDER_WAIT_PAINT)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //油漆做底
        $data['priming'] = WorkOrder::where('status', ORDER_PAINT)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待喷漆
        $data['waiting_painting'] = WorkOrder::where('status', ORDER_WAIT_SPRAY_PAINT)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //喷漆
        $data['painting'] = WorkOrder::where('status', ORDER_SPRAY_PAINT)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待钣金装复
        $data['waiting_reassembly'] = WorkOrder::where('status', ORDER_WAIT_PLATE_INSTALL)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //钣金装复
        $data['reassembly'] = WorkOrder::where('status', ORDER_PLATE_INSTALL)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待抛光
        $data['waiting_polishing'] = WorkOrder::where('status', ORDER_WAIT_POLISH)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //抛光
        $data['polishing'] = WorkOrder::where('status', ORDER_POLISH)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //等待机电装配
        $data['waiting_electrical'] = WorkOrder::where('status', ORDER_WAIT_ELECTROMECHANICAL_INSTALL)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //机电装配
        $data['electrical'] = WorkOrder::where('status', ORDER_ELECTROMECHANICAL_INSTALL)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //洗车质检
        $data['inspection'] = WorkOrder::where('status', ORDER_QUALITY_TESTING)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        //待结算
        $data['settlement'] = WorkOrder::where('status', ORDER_WAIT_PAY)
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->count();

        return $this->success($data);
    }

    public function createInfo()
    {
        $user = Auth::user();

        $brand = $user->workshop->brand;

        $cars = Car::where('brand_id', $brand->id)->get();

        $advisors = Administrator::whereHas('roles', function($query) use($user) {
            $query->where('role_id', 3);
        })->where('workshop_id', $user->workshop_id)->get();

        return $this->success([
            'brand' => $brand,
            'cars' => $cars,
            'advisors' => $advisors
        ]);
    }

    public function detail(Request $request)
    {
        $param = $request->all();

        $work_order_id = $param['work_order_id'];
        $order = WorkOrderService::detail($work_order_id);
        $order->car_title = $order->car->title;

        $paint_parts = WorkOrderComponent::where('work_order_id', $work_order_id)->where('type', COMPONENT_SPRAY_PAINT)->get();

        if ($paint_parts) {
            foreach ($paint_parts as $key => &$value) {
                $value['partId'] = $value['component_maintenance_id'];
                $value['partName'] = $value['title'];
                $value['position'] = componentTitle($value['position_type']);
                $value['damageLevel'] = "{$value['damage_level_type']}";
                $value['ratio'] = $value['damage_coefficient'];
            }

            $order->paint_parts = $paint_parts;
        } else {
            $order->paint_parts = '';
        }

        $sheet_metal_parts = WorkOrderComponent::where('work_order_id', $work_order_id)->where('type', COMPONENT_SHEET_METAL)->get();

        if ($sheet_metal_parts) {
            foreach ($sheet_metal_parts as $key => &$value) {
                $value['partId'] = $value['component_maintenance_id'];
                $value['partName'] = $value['title'];
                $value['position'] = componentTitle($value['position_type']);
                $value['damageLevel'] = "{$value['damage_level_type']}";
                $value['ratio'] = $value['damage_coefficient'];

            }

            $order->sheet_metal_parts = $sheet_metal_parts;
        } else {
            $order->sheet_metal_parts = '';
        }

        $dispatch = WorkOrderDispatch::where('work_order_id', $work_order_id)->get()->toArray();

        foreach ($dispatch as $key => &$value) {
            $value['repair_status_title'] = repairStatusTitle($value['repair_status']);
        }

        $operation_log = \App\Models\WorkOrderOperationLog::where('work_order_id', $work_order_id)->get();

        foreach ($operation_log as $key => &$value) {
            if ($value['user_id']) {
                $value['user_name'] = $value->user->name;
            }

            if ($value['processes_archives_id']) {
                $value['processes_archives_title'] = $value->processesArchives->title;
            }

            $value['operation_name'] = $value->operation->name;
        }

        $stop_rework = WorkOrderStopRework::where('work_order_id', $work_order_id)->get();

        foreach ($stop_rework as $key => &$value) {
            $value['processes_archives_title'] = $value->processesArchives->title;
            $value['stop_rework_title'] = $value->stopReworkReason->title;
            $value['type_title'] = stopReworkTitle($value->type);
        }

        return $this->success([
            'order' => $order,
            'operation_log' => $operation_log,
            'stop_rework' => $stop_rework,
            'dispatch_log' => $dispatch,
            'last_dispatch' => end($dispatch)
        ]);
    }

    public function componentMaintenance(Request $request)
    {
        $param = $request->all();

        $where = [];

        if ($param) {
            $where['position_type'] = positionType($param['position_type']);
            $where['type'] = componentType($param['type']);
        }

        $component = ComponentMaintenance::where($where)->where('status', DEFAULT_TRUE)->get();

        if ($component) {
            foreach ($component as $key => &$value) {
                $value['name'] = $value['title'];
                $value['damage_level_type'] = 'light';
                $value['ratio'] = 1;
                $value['position_title'] = componentTitle($value['position_type'], false);
                $value['position'] = $param['position_type'];
            }
        }

        return $this->success($component);
    }

    public function create(Request $request)
    {
        $param = $request->all();
        $user = Auth::user();

        $param['user_id'] = $user->id;
        $param['user_name'] = $user->name;
        $param['workshop_id'] = $user->workshop_id;

        if (isset($param['paint_parts'])) {
            $param['paint_parts'] = json_decode($param['paint_parts'], true);

            foreach ($param['paint_parts'] as $key => &$value) {
                $value['id'] = $value['partId'];
                $value['title'] = $value['partName'];
                $value['position_type'] = positionType($value['position']);
                $value['damage_level_type'] = $value['damageLevel'];
                $value['damage_new_coefficient'] = $value['ratio'];
            }
        }

        if (isset($param['sheet_metal_parts'])) {
            $param['sheet_metal_parts'] = json_decode($param['sheet_metal_parts'], true);

            foreach ($param['sheet_metal_parts'] as $key => &$value) {
                $value['id'] = $value['partId'];
                $value['title'] = $value['partName'];
                $value['position_type'] = positionType($value['position']);
                $value['damage_level_type'] = $value['damageLevel'];
                $value['damage_new_coefficient'] = $value['ratio'];
            }
        }

        WorkOrderService::orderCreate($param, 2);

        return $this->success();
    }

    public function update(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $param['user_id'] = $user->id;
        $param['workshop_id'] = $user->workshop_id;

        if (isset($param['paint_parts'])) {
            $param['paint_parts'] = json_decode($param['paint_parts'], true);

            foreach ($param['paint_parts'] as $key => &$value) {
                $value['id'] = $value['partId'];
                $value['title'] = $value['partName'];
                $value['position_type'] = positionType($value['position']);
                $value['damage_level_type'] = $value['damageLevel'];
                $value['damage_new_coefficient'] = $value['ratio'];
            }
        }

        if (isset($param['sheet_metal_parts'])) {
            $param['sheet_metal_parts'] = json_decode($param['sheet_metal_parts'], true);

            foreach ($param['sheet_metal_parts'] as $key => &$value) {
                $value['id'] = $value['partId'];
                $value['title'] = $value['partName'];
                $value['position_type'] = positionType($value['position']);
                $value['damage_level_type'] = $value['damageLevel'];
                $value['damage_new_coefficient'] = $value['ratio'];
            }
        }

        WorkOrderService::orderUpdate($param, 2);

        return $this->success();
    }

    public function orderAll(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $user_workshop_id = $user->workshop_id;

        $keyword = '';

        if (isset($param['keywords'])) {
            $keyword = $param['keywords'];
        }

        $data = WorkOrder::where('status', webOrderStatus($param['type']))
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->orderBy('id', 'desc')
            ->get();

        foreach ($data as $key => $value) {
            $value['brand_title'] = $value->brand->title;
            $value['car_title'] = $value->car->title;
            $value['service_advisor_name'] = $value->serviceAdvisor->name;
            $processes_archives = ProcessesArchive::where('sort', $value['status'])->first();

            $order_dispatch = WorkOrderDispatch::where('work_order_id', $value['id'])
                ->where('processes_archives_id', $processes_archives->id)
                ->first();

            if ($order_dispatch) {
                $value['dispatch_id'] = $order_dispatch->id;
                $value['manager'] = $order_dispatch->user_name;
                $value['wait_time'] = formatTimeDifference($order_dispatch->created_at, date('Y-m-d H:i:s'));
            } else {
                $value['wait_time'] = formatTimeDifference($value->created_at, date('Y-m-d H:i:s'));
            }
        }

        return $this->success(['data' => $data, 'count' => count($data)]);
    }

    public function moveBack(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $order_id = $param['work_order_id'];

        $order = \App\Models\WorkOrder::where('id', $order_id)->first();

        $processes_archives = ProcessesArchive::where('sort', $order->status)->first();

        $desc_dispatch = WorkOrderDispatch::where('work_order_id', $order_id)
            ->orderBy('id', 'desc')
            ->first();

        WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('processes_archives_id', $processes_archives->id)
            ->delete();

        $desc_dispatch->repair_status = PROCESSES_IN;
        $desc_dispatch->save();

        $order->status = $order->status - 1;
        $order->save();

        $back_processes_archives = ProcessesArchive::where('sort',  $order->status)->first();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '后退工单-进入'.$back_processes_archives->title,
            'type' => 2,
            'operation_id' => $user->id
        ]);

        return $this->success();
    }

    public function orderProcessesArchivesAll(Request $request)
    {
        $param = $request->all();

        $dispatch = WorkOrderDispatch::where('work_order_id', $param['work_order_id'])->get();

        if ($dispatch) {
            foreach ($dispatch as $key => $value) {
                $value->processesArchives->dispatch_id = $value->id;
                $processes_archives[] = $value->processesArchives;
            }
        }

        return $this->success($processes_archives ? array_slice($processes_archives, 0, -1) : []);
    }

    public function processesArchivesAll(Request $request)
    {
        $processes_archives = ProcessesArchive::where('status', DEFAULT_TRUE)->orderBy('sort', 'asc')->get();

        return $this->success($processes_archives);
    }

    public function reworkAll(Request $request)
    {
        $rework = StopReworkReason::where('status', DEFAULT_TRUE)->where('type', REWORK_REASON)->get();

        return $this->success($rework);
    }

    public function stopAll(Request $request)
    {
        $stop = StopReworkReason::where('status', DEFAULT_TRUE)->where('type', STOP_REASON)->get();

        return $this->success($stop);
    }

    public function technicianAll(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $user_process = UserProcess::where('workshop_id', $user->workshop_id)->whereJsonContains('processes_archives_ids', $param['id'])->get();

        if ($user_process) {
            foreach ($user_process as $key => &$value) {
                $value['user_name'] = $value->user->name;
                $value['dispatch_count'] = WorkOrderDispatch::where('user_id', $value['user_id'])->where('repair_status', PROCESSES_IN)->count();
            }
        }

        return $this->success($user_process);
    }

    public function assign(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $processes_archive_id = $param['processes_archive_id'];
        $order_id = $param['work_order_id'];

        $processes_archives = ProcessesArchive::where('id', $processes_archive_id)->first();

        \App\Models\WorkOrder::where('id', $order_id)->update([
            'status' => $processes_archives['sort'],
            'is_rework' => DEFAULT_FALSE
        ]);

        $operation_log_param = [
            'work_order_id' => $param['work_order_id'],
            'content' => '派工-'.$processes_archives->title,
            'type' => 2,
            'operation_id' => $user->id
        ];

        //原有的派工维修类型都改为结束
        WorkOrderDispatch::where('work_order_id', $order_id)->update([
            'repair_status' => PROCESSES_AFTER,
            'actual_end_at' => date('Y-m-d H:i:s')
        ]);

        if ($param['technician_id']) {
            $technician = Administrator::where('id', $param['technician_id'])->first();
            WorkOrderDispatch::create([
                'work_order_id' => $order_id,
                'processes_archives_id' => $processes_archive_id,
                'processes_archives_title' => $processes_archives->title,
                'user_id' => $technician['id'],
                'user_name' => $technician['name'],
                'repair_status' => PROCESSES_IN,
                'actual_start_at' => date('Y-m-d H:i:s')
            ]);

            $operation_log_param = array_merge($operation_log_param, [
                'user_id' => $technician['user_id'],
                'processes_archives_id' => $processes_archive_id,
            ]);
        } else {
            WorkOrderDispatch::create([
                'work_order_id' => $order_id,
                'processes_archives_id' => $processes_archive_id,
                'processes_archives_title' => $processes_archives->title,
                'repair_status' => PROCESSES_IN,
                'actual_start_at' => date('Y-m-d H:i:s')
            ]);
        }

        WorkOrderOperationLog::save($operation_log_param);

        return $this->success();
    }

    public function stop(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $order_id = $param['work_order_id'];
        $stop_id = $param['stop_id'];
        $dispatch_id = $param['dispatch_id'];

        $dispatch = WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('id', $dispatch_id)
            ->first();

        //创建中断记录
        WorkOrderStopRework::create([
            'work_order_id'  => $order_id,
            'processes_archives_id' => $dispatch->processes_archives_id,
            'stop_rework_reason_id' => $stop_id,
            'order_dispatch_id' => $dispatch_id,
            'content' => $param['content'],
            'user_id' => $dispatch->user_id,
            'type' => STOP_REASON,
            'operation_id' => $user->id
        ]);

        //更改中断状态
        \App\Models\WorkOrder::where('id', $order_id)->update([
            'is_stop' => DEFAULT_TRUE
        ]);

        //订单中断后，新更改的工序状态修改
        $dispatch->is_stop = DEFAULT_TRUE;
        $dispatch->save();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '中断工单-'.$dispatch->processes_archives_title,
            'type' => 2,
            'operation_id' => $user->id
        ]);

        return $this->success();
    }

    public function stopContinue(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $order_id = $param['work_order_id'];
        $dispatch_id = $param['dispatch_id'];

        //更改中断状态
        \App\Models\WorkOrder::where('id', $order_id)->update([
            'is_stop' => DEFAULT_FALSE
        ]);

        $dispatch =  WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('id', $dispatch_id)
            ->first();

        $dispatch->is_stop = DEFAULT_FALSE;
        $dispatch->save();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '继续工单-'.$dispatch->processes_archives_title,
            'type' => 2,
            'operation_id' => $user->id
        ]);

        return $this->success();
    }

    public function rework(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $processes_archive_id = $param['processes_archive_id'];
        $order_id = $param['work_order_id'];
        $technician_id = $param['technician_id'];
        $rework_id = $param['rework_id'];
        $dispatch_id = $param['dispatch_id'];
        $old_dispatch_id = $param['old_dispatch_id'];

        //查询旧派工
        $old_dispatch = WorkOrderDispatch::find($old_dispatch_id);

        //创建返工记录
        WorkOrderStopRework::create([
            'work_order_id'  => $order_id,
            'processes_archives_id' => $processes_archive_id,
            'original_processes_archives_id' => $old_dispatch->processes_archives_id,
            'stop_rework_reason_id' => $rework_id,
            'order_dispatch_id' => $dispatch_id,
            'content' => $param['content'],
            'user_id' => $technician_id,
            'type' => REWORK_REASON,
            'operation_id' => $user->id
        ]);


//         WorkOrderDispatch::where('id', $dispatch_id)->delete();

        //查询工序
        $processes_archive = ProcessesArchive::find($processes_archive_id);

        //更改订单为内返及订单状态
        \App\Models\WorkOrder::where('id', $order_id)->update([
            'is_rework' => DEFAULT_TRUE,
            'status' => $processes_archive->sort
        ]);

        //订单内返后，新更改的工序状态修改
        WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('processes_archives_id', $processes_archive_id)
            ->update([
                'repair_status' => PROCESSES_IN
            ]);

        //旧工序删除
        $old_dispatch->delete();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '返工工单-进入'.$processes_archive->title,
            'type' => 2,
            'operation_id' => $user->id
        ]);

        return $this->success();
    }

    public function settlement(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $order_id = $param['work_order_id'];

        \App\Models\WorkOrder::where('id', $order_id)->update([
            'status' => ORDER_PAY,
            'settlement_at' => date('Y-m-d H:i:s')
        ]);

        WorkOrderDispatch::create([
            'work_order_id' => $order_id,
            'processes_archives_title' => '结算',
            'processes_archives_id' => 18, //固定结算ID
            'repair_status' => PROCESSES_AFTER,
            'actual_start_at' => date('Y-m-d H:i:s')
        ]);

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '结算工单',
            'type' => 2,
            'operation_id' => $user->id
        ]);

        return $this->success();
    }

    public function workLogAll(Request $request)
    {
        $param = $request->all();

        $dispatch = WorkOrderDispatch::where('work_order_id', $param['order_id'])->get();

        foreach ($dispatch as $key => &$value) {
            $value['repair_status_title'] = repairStatusTitle($value['repair_status']);

            $value['actual_start_ats'] = date("m-d H:i", strtotime($value['actual_start_at']));
            $value['actual_end_ats'] = date("m-d H:i", strtotime($value['actual_end_at']));
        }

        return $this->success($dispatch);
    }

    public function operationLogAll(Request $request)
    {
        $param = $request->all();

        $dispatch = \App\Models\WorkOrderOperationLog::where('work_order_id', $param['order_id'])->get();

        foreach ($dispatch as $key => &$value) {
            if ($value['user_id']) {
                $value['user_name'] = $value->user->name;
            }

            if ($value['processes_archives_id']) {
                $value['processes_archives_title'] = $value->processesArchives->title;
            }

            $value['operation_name'] = $value->operation->name;
        }

        return $this->success($dispatch);
    }

    public function photoLogAll(Request $request)
    {
        $param = $request->all();

        $pics = WorkOrderPic::where('work_order_id', $param['order_id'])->get();

        foreach ($pics as $key => &$value) {
            $value['created_ats'] = date("m-d H:i", strtotime($value['created_at']));
        }

        return $this->success($pics);
    }

    public function photoSave(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $order_id = $param['order_id'];

        WorkOrderPic::create([
            'work_order_id' => $order_id,
            'user_id' => $user->id,
            'user_name' => $user->name,
            'pics' => $param['url'],
            'processes_archives_id' => $param['processes_archives_id'],
            'processes_archives_title' => $param['processes_archives_title'],
            'dispatch_id' => $param['dispatch_id'],
        ]);

        $pics = WorkOrderPic::where('work_order_id', $param['order_id'])->get();

        foreach ($pics as $key => &$value) {
            $value['created_ats'] = date("m-d H:i", strtotime($value['created_at']));
        }

        WorkOrderOperationLog::save([
            'work_order_id' => $param['order_id'],
            'content' => "上传操作图-订单ID：{$param['order_id']}-工序：{$param['processes_archives_title']}-图片地址：{$param['url']}",
            'type' => 2,
            'processes_archives_id' => $param['processes_archives_id'],
            'operation_id' => $user->id
        ]);

        return $this->success($pics);
    }

    public function reworkStopLogAll(Request $request)
    {
        $param = $request->all();

        $stop_rework = WorkOrderStopRework::where('work_order_id', $param['order_id'])->get();

        foreach ($stop_rework as $key => &$value) {
            $value['processes_archives_title'] = $value->processesArchives->title;
            $value['stop_rework_title'] = $value->stopReworkReason->title;
            $value['type_title'] = stopReworkTitle($value->type);
        }

        return $this->success($stop_rework);
    }

    public function photoDelete(Request $request)
    {
        $param = $request->all();

        $user = Auth::user();

        $pic = WorkOrderPic::where('id', $param['photo_id'])->first();

        $old_pic = $pic;

        $pics = WorkOrderPic::where('work_order_id', $param['order_id'])->get();

        foreach ($pics as $key => &$value) {
            $value['created_ats'] = date("m-d H:i", strtotime($value['created_at']));
        }

        WorkOrderOperationLog::save([
            'work_order_id' => $param['order_id'],
            'content' => "删除操作图-订单ID：{$param['order_id']}-工序：{$old_pic['processes_archives_title']}-图片ID：{$param['photo_id']}-图片地址：{$old_pic['pics']}",
            'type' => 2,
            'processes_archives_id' => $old_pic['processes_archives_id'],
            'operation_id' => $user->id
        ]);

        return $this->success($pics);
    }

    public function getList(Request $request)
    {
        $user = Auth::user();

        $type = $request->get('pageType');
        $perPage = $request->input('per_page', 10);

        $keyword = '';

        $param = $request->all();

        if (isset($param['keywords'])) {
            $keyword = $param['keywords'];
        }

        $query = \App\Models\WorkOrder::query();

        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');

        // 根据不同类型添加查询条件
        switch ($type) {
            case 'in_factory':
                $query->whereBetween('status', [0, 16])
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'damage_assessment':
                $query->where('');
                break;
            case 'in_production':
                $query->whereBetween('status', [1, 15])
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'pending_repair':
                $query->where('status', 0)
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'rework':
                $query->where('is_return', DEFAULT_TRUE)
                    ->whereOr('is_rework', DEFAULT_TRUE)
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'today_in':
                $query->whereBetween('created_at', [$today_start, $today_end])
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'interrupted':
                $query->where('is_stop', DEFAULT_TRUE)
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%");
                break;
            case 'delayed':
                $query->where('pre_delivery_at', '<' ,date('Y-m-d H:i:s'))
                    ->where('status', '<', ORDER_WAIT_PAY)
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'due_today':
                $query->whereBetween('pre_delivery_at', [$today_start, $today_end])
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'delivered_today':
                $query->whereBetween('settlement_at', [$today_start, $today_end])
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
            case 'tomorrow':
                $tomorrow_start = date('Y-m-d 00:00:00', strtotime('+1 day'));
                $tomorrow_end = date('Y-m-d 23:59:59', strtotime('+1 day'));

                $query->whereBetween('pre_delivery_at', [$tomorrow_start, $tomorrow_end])
                    ->where('car_number', 'like', "%{$keyword}%")
                    ->whereOr('user_name', 'like', "%{$keyword}%")
                    ->where('workshop_id', $user->workshop_id);
                break;
        }

        $data = $query->paginate($perPage);

        foreach ($data->items() as $key => &$value) {
            $value->brand_title = $value->brand->title;
            $value->car_title = $value->car->title;
            $value->service_advisor_name = $value->serviceAdvisor->name;

            $dispatch = WorkOrderDispatch::where('work_order_id', $value->id)->orderBy('id', 'desc')->first();

            if ($dispatch) {
                $value->processes_archives_title = $dispatch->processes_archives_title;
                $value->dispatch_user_name = $dispatch->user_name;
            }

            if ($value->opening_at) {
                $value->opening_ats = date('Y-m-d H:i', strtotime($value->opening_at));
            }

            if ($value->pre_delivery_at) {
                $value->pre_delivery_ats = date('Y-m-d H:i', strtotime($value->pre_delivery_at));
            }
        }

        return $this->success(['data' => $data->items(), 'total' => $data->total()]);
    }

    public function technicianList(Request $request)
    {
        $user = Auth::user();

        $technician = Administrator::whereHas('roles', function($query) use($user) {
            $query->where('role_id', 2);
        })->where('workshop_id', $user->workshop_id)->get();

        return $this->success($technician);
    }

    public function technicianData(Request $request)
    {
        $keyword = '';

        $param = $request->all();

        $user = Auth::user();

        if (isset($param['keywords']) && $param['keywords'] != 0) {
            $keyword = $param['keywords'];
        }

        $technician = Administrator::whereHas('roles', function($query) use($user) {
            $query->where('role_id', 2);
        })->where('workshop_id', $user->workshop_id)
            ->where('name', 'like', "%{$keyword}%")
            ->get();

        if ($technician) {
            foreach ($technician as $key => &$value) {
                $orders = [];
                $dispatch_processes_in = WorkOrderDispatch::where('user_id', $value['id'])
                    ->where('repair_status', PROCESSES_IN)
                    ->get()
                    ->toArray();

                $value['dispatch_in_count'] = count($dispatch_processes_in);

                $value['quantity_in_count'] = 0;

                if ($dispatch_processes_in) {
                    foreach ($dispatch_processes_in as $k => $val) {
                        $value['quantity_in_count'] += WorkOrderComponent::where('work_order_id', $val['work_order_id'])
                            ->sum('standard_quantity_base');

                        $order = WorkOrder::find($val['work_order_id']);
                        $order->dispatch_title = $val['processes_archives_title'];
                        $order->wait_time = formatTimeDifference($val['created_at'], date('Y-m-d H:i:s'));

                        $orders[] = $order;
                    }
                }

                $value['orders'] = $orders ?? '';

                $today_start = date('Y-m-d 00:00:00');
                $today_end = date('Y-m-d 23:59:59');

                $dispatch_processes_end = WorkOrderDispatch::where('user_id', $value['id'])
                    ->whereBetween('actual_end_at', [$today_start, $today_end])
                    ->get();

                $value['dispatch_end_count'] = count($dispatch_processes_end);

                $value['quantity_end_count'] = 0;

                if ($dispatch_processes_end) {
                    foreach ($dispatch_processes_end as $k => $val) {
                        $value['quantity_end_count'] += WorkOrderComponent::where('work_order_id', $val['work_order_id'])
                            ->sum('standard_quantity_base');
                    }
                }
            }
        }

        return $this->success($technician);
    }

    public function consultantList()
    {
        $user = Auth::user();

        $consultant = Administrator::whereHas('roles', function($query) use($user) {
            $query->where('role_id', 3);
        })->where('workshop_id', $user->workshop_id)->get();

        return $this->success($consultant);
    }

    public function consultantData(Request $request)
    {
        $user = Auth::user();

        $where = [];

        $param = $request->all();

        if ($param['car_number']) {
            $where[] = ['car_number', 'like', "%{$param['car_number']}%"];
        }

        $today_start = date('2025-01-01 00:00:00');
//        $today_end = date('Y-m-d 23:59:59');

        if ($param['opening_at']) {
            $today_start = date("{$param['opening_at']} 00:00:00");
        }

        if ($param['settlement_at']) {
            $where[] = ['settlement_at', '<', date("{$param['settlement_at']} 23:59:59")];
        }

        if ($param['user_id']) {
            $where['service_advisor_id'] = $param['user_id'];
        }

        $data = WorkOrder::where('opening_at', '>', $today_start)
            ->where('status', '<', ORDER_PAY)
            ->where($where)
            ->where('workshop_id', $user->workshop_id)
            ->get();

        if ($data) {
            foreach ($data as $key => &$value) {
                $dispatch = WorkOrderDispatch::where('work_order_id', $value['id'])->where('processes_archives_id', '<', 11)->get()->toArray();
                $new_dispatch = processesArchivesMerge($dispatch);

                $value['dispatch'] = $new_dispatch;

                $value['service_advisor_name'] = $value->serviceAdvisor->name;
            }
        }

        return $this->success($data);
    }
}